var icdev = 0; //设备句柄
var lock = new Lock()
var data = undefined
var resetData = undefined
var uid = undefined
var msg = {} ;
var layer = layui.layer
var form = layui.form
var status = 0 // 0 未复位   1 已复位
var reader = getReader(async function(){
    // 连接USB读卡器
    try {
        reader.connectUsb(); //连接usb设备
        await lock.wait()
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}); //获取reader对象, getReader会自动连接ReaderService服务
if (reader == null) {
    alert('您的浏览器不支持读写器服务.');
}

// 设置回调
reader.onResult(function (ret) {
    data = ret
    console.log("返回："+data.resultData)
    lock.notify(data)
    //执行成功
    if (ret.result == 0) {
        switch (ret.functionId) {
            case READER_CMD._reader_server_connect:
                break;
            case READER_CMD._reader_cmd_connect:
                icdev = parseInt(ret.resultData); //连接成功后, resultData 为设备句柄
                msg.value = msg.value + "读写器连接成功.\n";
                break;
            case READER_CMD._reader_cmd_disconnect:
                msg.value = msg.value + "读写器断开连接成功.\n";
                break;
            case READER_CMD._reader_cmd_beep:
                msg.value = msg.value + "读写器鸣响成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_card:
            case READER_CMD._reader_cmd_rf_card_b:
                msg.value = msg.value + "寻卡成功, 卡片序列号: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset:
                msg.value = msg.value + "非接触式 TypeA CPU 卡复位成功. 复位信息: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset_b:
                msg.value = msg.value + "非接触式 TypeB CPU 卡复位成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_halt:
            case READER_CMD._reader_cmd_rf_halt_b:
                msg.value = msg.value + "终止卡片操作成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_auth_key:
                msg.value = msg.value + "Ultralight C 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_uev_auth_key:
                msg.value = msg.value + "Ultralight EV 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_u_read:
                msg.value = msg.value + "Ultralight / Ultralight C 读数据成功. 读取到的数据: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_u_write:
                msg.value = msg.value + "Ultralight / Ultralight C 写数据成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_change_key:
                msg.value = msg.value + "更改  Ultralight C 密码成功.\n";
                break;
        }
    } else {
        //失败打印错误信息
        msg.value = msg.value + ret.resultData + "\n";
    }
    // console.log(data)
});


// 定时寻卡
async function find_card(){
    try {
        reader.rfCard(icdev, 1);
        await lock.wait()
        uid = data.resultData
        console.log(uid)
        if(uid != "请求失败。" && uid != "设备未连接。"){
            clearInterval(timer)
            status = 1
            cardNo = uid
            $("input[name='cardNo']").val(uid)
            form.render()
        }
        reader.mifareCpuReset(icdev);
        await lock.wait()
        resetData = data.resultData
    } catch (e) {
        console.log(e)
        // msg.value = msg.value + e.Message + "\n";
    }
}

timer = setInterval(find_card , 1000)
async function write(){
    if(status == 1) {
        var cz2 = $("#cz2").val();
        var index = layer.confirm("确认开卡?,在开卡过程中请勿将卡片拿开" , async function(){
            var index2 = layer.load(1)

            if(resetData.startsWith("107880B002209000")) {
                // 1.查看目录是否存在
                reader.mifareCpuTransmit(icdev , "00A40000021001")
                await lock.wait()
                if(data.resultData != "6A82" && data.resultData != "6D00" && data.resultData != "6A80") {
                    layer.closeAll()
                    layer.msg("卡已被使用,无法重复写卡")
                    return false
                }
                // 外部认证
                var wbrz = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                $.ajax({
                    url:HOST+"cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=3" ,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async:false,
                    success:function(res){
                        if (res.code == 200) {
                            wbrz = "0082000008" + res.data
                        }else {
                            wbrz = undefined
                            layer.msg(res.msg);
                        }
                    }
                })
                if(wbrz == undefined) {
                    layer.close(index);
                    layer.close(index2);
                    return
                }
                reader.mifareCpuTransmit(icdev , wbrz) ;
                await lock.wait()
                /*if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }*/

                // 请求开卡指令
                var uuID = $("#kk").val();
                $.ajax({
                    url:HOST+"cpu_card/create_card?type=1&cid="+uid+"&uid="+GetQueryString("id")+"&ast="+resetData+"&random=&uuID="+uuID ,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async:false ,
                    success:function(res) {
                        if(res.code == 200) {
                            result = res.data
                        }else{
                            layer.msg(res.msg);

                            result = undefined
                        }
                    }
                })

                if(result == undefined) {
                    layer.close(index);
                    layer.close(index2);
                    return
                }

                // 擦除卡信息
                reader.mifareCpuTransmit(icdev , "800E000000") ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 建立key文件
                reader.mifareCpuTransmit(icdev , "80E00000073F00C001FAFFFF")
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置钱包主控秘钥
                reader.mifareCpuTransmit(icdev , result.qb) ;
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置应用主控秘钥
                reader.mifareCpuTransmit(icdev , result.root) ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建目录
                reader.mifareCpuTransmit(icdev , "80E01001113821B6F0F095FFFFA00000000386980701")
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 进入目录
                reader.mifareCpuTransmit(icdev , "00A4040009A00000000386980701")
                await lock.wait() ;
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建秘钥文件
                reader.mifareCpuTransmit(icdev , "80E00000073F024101FADFDA")
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置钱包主控秘钥 目录下
                reader.mifareCpuTransmit(icdev , result.dir_qb)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置目录秘钥
                reader.mifareCpuTransmit(icdev , result.dir)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置pin
                reader.mifareCpuTransmit(icdev , result.pin) ;
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 消费秘钥
                reader.mifareCpuTransmit(icdev , result.xf)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置圈存秘钥
                reader.mifareCpuTransmit(icdev , result.qc)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 设置tac秘钥
                reader.mifareCpuTransmit(icdev , result.tac)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 创建文件
                reader.mifareCpuTransmit(icdev , result.file)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 选择文件
                reader.mifareCpuTransmit(icdev , result.select_file)
                await lock.wait()
                if(checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }

                // 写文件
                for(var i in result.write_file) {
                    reader.mifareCpuTransmit(icdev , result.write_file[i])
                    await lock.wait()
                    if(checkRs() != undefined) {
                        layer.closeAll()
                        layer.msg(checkRs())
                        return
                    }
                }
                layer.msg("开卡成功")
                reader.rfHalt(icdev);
                setTimeout(function(){
                    layer.closeAll() ;
                    parent.location.reload()
                } , 1000)
            }else {
                // 1.查看目录是否存在
                reader.mifareCpuTransmit(icdev, "00A40000021001")
                await lock.wait()
                if (data.resultData != "6A82" && data.resultData != "6D00" && data.resultData != "6A80") {
                    layer.closeAll()
                    layer.msg("卡已被使用,无法重复写卡")
                    return false
                }
                // 获取随机数
                var result = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return false
                }
                // 请求开卡指令
                result = undefined
                var uuID = $("#kk").val();
                $.ajax({
                    url: HOST+"cpu_card/create_card?type=0&cid=" + uid + "&uid=" + GetQueryString("id") + "&ast=" + resetData + "&random=" + data.resultData + "&uuID=" + uuID,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        if (res.code == 200) {
                            result = res.data
                        } else {
                            layer.msg(res.msg)
                        }
                    }
                })
                if (result == undefined) {
                    layer.closeAll()
                    layer.msg("网络异常,无法完成开卡")
                    return
                }
                // 创建mf
                reader.mifareCpuTransmit(icdev, result.kaika);
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 外部认证
                var wbrz = undefined
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=1",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                if (result == undefined) {
                    layer.closeAll()
                    layer.msg("网络异常,无法完成开卡")
                    return
                }
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                // 设置根目录密钥
                reader.mifareCpuTransmit(icdev, result.root);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 创建文件夹
                await create_dir(result.create_dir)
                reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 目录外部认证
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=2",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                // 设置目录密钥
                reader.mifareCpuTransmit(icdev, result.dir);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 设置消费密钥
                reader.mifareCpuTransmit(icdev, result.xf);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 5.设置圈存密钥
                reader.mifareCpuTransmit(icdev, result.qc);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 6.设置TAC密钥
                reader.mifareCpuTransmit(icdev, result.tac);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 7.设置PIN密码
                reader.mifareCpuTransmit(icdev, result.pin);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 进入目录
                reader.mifareCpuTransmit(icdev, "00A40000021001");  // 进入目录
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                // 目录外部认证
                reader.mifareCpuTransmit(icdev, "0084000004");
                await lock.wait();
                $.ajax({
                    url: HOST+"cpu_card/certification?cid=" + uid + "&random=" + data.resultData + "&type=2",
                    beforeSend: function(request) {
                        request.setRequestHeader("token", layui.data('local_store').token);
                    },
                    async: false,
                    success: function (res) {
                        wbrz = "0082000008" + res.data
                    }
                })
                reader.mifareCpuTransmit(icdev, wbrz);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                for (var i in result.createFiles) {
                    // 8.创建文件
                    reader.mifareCpuTransmit(icdev, result.createFiles[i])
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.closeAll()
                        layer.msg(checkRs())
                        return
                    }
                }
                // 写文件
                reader.mifareCpuTransmit(icdev, result.select_file);
                await lock.wait()
                if (checkRs() != undefined) {
                    layer.closeAll()
                    layer.msg(checkRs())
                    return
                }
                for (var i in result.write_file) {
                    reader.mifareCpuTransmit(icdev, result.write_file[i])
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.closeAll()
                        layer.msg(checkRs())
                        return
                    }
                }

                var money = undefined
                // 查询用户余额,将余额写入卡片
                $.ajax({
                    url: HOST+"userInfo/staff_id?id=" + GetQueryString("id"),
                    async: false,
                    success: function (res) {
                        if (res.code == 200) {
                            money = res.data.cardBalance;
                        }
                    }
                })
                if (money != 0) {
                    if (money == undefined) {
                        layer.msg("金额写入失败")
                        return
                    }
                    var map = undefined
                    // 请求充值预处理
                    money = money * 100
                    $.ajax({
                        url: HOST+"cpu_card/chongzhi_prepare?money=" + money + "&czUUID=" + cz2 + "&cid=" + uid,
                        async: false,
                        success: function (res) {
                            if (res.code == 600) {
                                layer.msg(data.msg);
                            } else if (res.code == 200) {
                                map = res.data
                            } else {
                                layer.msg(data.msg)
                            }
                        }
                    })
                    if (map == undefined) {
                        layer.msg("网络异常,无法完成充值")
                        return false
                    }
                    reader.mifareCpuTransmit(icdev, map.select_file)
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.msg(checkRs())
                        return false
                    }
                    reader.mifareCpuTransmit(icdev, map.select_dir)
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.msg(checkRs())
                        return false
                    }
                    reader.mifareCpuTransmit(icdev, map.pin)
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.msg(checkRs())
                        return false
                    }
                    reader.mifareCpuTransmit(icdev, map.insert)
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.msg(checkRs())
                        return false
                    }

                    var cz1 = $("#cz1").val();
                    map = undefined
                    $.ajax({
                        url: HOST+"cpu_card/chongzhi?uid=" + GetQueryString("id") + "&info=" + data.resultData + "&money=" + money + "&czUUID=" + cz1,
                        async: false,
                        success: function (res) {
                            if (res.code == 600) {
                                layer.msg(data.msg);
                            } else if (res.code == 200) {
                                map = res.data
                            }
                        }
                    })
                    reader.mifareCpuTransmit(icdev, map.chongzhi)
                    await lock.wait()
                    if (checkRs() != undefined) {
                        layer.msg(checkRs())
                        return false
                    }
                }
                layer.closeAll()
                layer.msg("开卡成功")
                reader.rfHalt(icdev);
                await lock.wait()
                parent.location.reload()
            }
        })
    }else{
        layer.msg("未识别到卡,请重新放置")
    }
}

// parent.location.reload()

// 创建目录
async function create_dir(str){
    try {
        // 进入根目录
        reader.mifareCpuTransmit(icdev, "00A40000023F00");
        await lock.wait()
        // 外部认证
        var wbrz = undefined
        reader.mifareCpuTransmit(icdev, "0084000004");
        await lock.wait() ;
        if(checkRs() != undefined) {
            layer.msg(checkRs())
            return
        }
        $.ajax({
            url:HOST+"cpu_card/certification?cid="+uid+"&random="+data.resultData+"&type=1" ,
            beforeSend: function(request) {
                request.setRequestHeader("token", layui.data('local_store').token);
            },
            async:false ,
            success:function(res){
                wbrz = "0082000008" + res.data
            }
        })
        if(wbrz == undefined) {
            layer.msg("网络异常,无法完成开卡")
            return
        }
        reader.mifareCpuTransmit(icdev , wbrz) ;
        await lock.wait()
        // 1.进入目录
        reader.mifareCpuTransmit(icdev, "00A40000021001");
        await lock.wait()
        if(data.resultData == "6A82") {
            // 建立目录
            reader.mifareCpuTransmit(icdev, str);
            await lock.wait()
        }
        // else{
        //     alert("目录已经存在")
        // }
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}


function checkRs(){
    switch(data.resultData) {
        case "6200":
            return "警告 信息未提供"
        case "6281":
            return "警告 回送数据可能"
        case "6282":
            return "警告 文件长度小于Le"
        case "6283" :
            return "警告 选中的文件无效"
        case "6284":
            return "警告 FCI格式与P2指定的不符"
        case "6300":
            return "警告 鉴别失败"
        case "63C2":
            return "警告 校验失败（允许重试次数2）"
        case "63C1":
            return "警告 校验失败（允许重试次数1）"
        case "6400":
            return "状态标志位没有变"
        case "6581":
            return "内存失败"
        case "6700":
            return "长度错误"
        case "6882" :
            return "不支持安全报文"
        case "6981":
            return "命令与文件结构不相容，当前文件非所需文件"
        case "6982":
            return "操作条件（AC）不满足，没有校验PIN"
        case "6983":
            return "您的卡已被锁定"
        case "6984":
            return "随机数无效，引用的数据无效"
        case "6985":
            return "使用条件不满足"
        case "6986":
            return "不满足命令执行条件（不允许的命令，INS有错）"
        case "6987":
            return "MAC丢失"
        case "6988":
            return "MAC不正确"
        case "698D":
            return "保留"
        case "6A80":
            return "数据域参数不正确"
        case "6A81":
            return "功能不支持；创建不允许；目录无效；应用锁定"
        case "6A82":
            return "该文件未找到"
        case "6A83":
            return "该记录未找到"
        case "6A84":
            return "文件预留空间不足"
        case "6A86":
            return "P1或P2不正确"
        case "6A88":
            return "引用数据未找到"
        case "6B00":
            return "参数错误"
        case "6C":
            return "Le长度错误"
        case "6E00":
            return "不支持的类：CLA有错"
        case "6F00":
            return "数据无效"
        case "6F01" :
            return "连接中断"
        case "6D00":
            return "不支持的指令代码"
        case "9301":
            return "您的卡余额不足"
        case "9302":
            return "MAC2错误"
        case "9303":
            return "应用被永久锁定"
        case "9401":
            return "您的卡余额不足"
        case "9402":
            return "交易计数器达到最大值"
        case "9403":
            return "密钥索引不支持"
        case "9406":
            return "所需MAC不可用"
        case "6900":
            return "不能处理"
        case "6901":
            return "命令不接受（无效状态）"
        case "61":
            return "正常 需发GET RESPONSE命令"
        case "6600":
            return  "接收通讯超时"
        case "6601":
            return "接收字符奇偶错"
        case "6602":
            return "校验和不对"
        case "6603":
            return "警告 当前DF文件无FCI"
        case "6604":
            return "警告 当前DF下无SF或KF"
        case "6E81":
            return "卡片已离开"
        default:
            return undefined
    }
}